// page/component/details/details.js
Page({
  data: {
    goods: {},
    goodsDetail:{},
    assess: 0,
    newPrice: 0,    



    evaluate: [], //评论
    evaluate1: [],

    evanum: 0, //评论数量

    showmore: false,

    shownum: 2,
    shownum1: 1,

    havemore: false,
    
    //详情页购物车数量
    cartNum: 0,
    show: false,//是否显示数量图标
    // totalNum: 0,
    // hasCarts: false,
    // curIndex: 0,
    // show: false,
    // scaleCart: false
    toView: 'hot',
    num: 1,
    detail: [],
    imgs: null,  //详情图片
    haveImgs :false,
    userID: null
  },

  addCount() {
    let num = this.data.num;
    num++;
    this.setData({
      num: num
    })
  },
   
  // 加入购物车
  addToCart() {
    let self = this;
    // const num = this.data.num;
    // let total = this.data.totalNum;

    self.setData({
      show: true,
      cartNum: self.data.cartNum+1
    })

   //向后台发送请求添加购物车
    console.log(self.data.goods);
    let vip = getApp().globalData.vipState;
    let price = 0;
    if (vip == 1) {
      price = self.data.goods.goodsPrice;
    }
    else{
      price = self.data.newPrice;
    }
    console.log('====================================');
    console.log(price);
    console.log('====================================');
    let userId = null;
    if (self.data.userID == null)
    {
      userId = wx.getStorageSync('userID');
    } else {
      userId = this.data.userID;
    }
    wx.request({
      url: 'https://localhost:80/cart/add',
      method: 'POST',
      data:{
        'cartGoods': {
          'goodsId': self.data.goods.goodsId,
          'goodsPrice': self.data.goodsPrice,
        },
        'cartNum' : 1,
        'cartPrice' : price,
        'cartUser' : userId,
      },
      success: res=> {
        console.log('成功');
      },
      error: res=> {
        console.log('失败！');
      }
    })


  },

  bindTap(e) {
    const Index = parseInt(e.currentTarget.dataset.index);
    this.setData({
      curIndex: Index
    });
  },

  cartOrder () {
    wx.switchTab({
      url: '../cart/cart'
    })
  },

  //评论展示更多
  showmore(){
    console.log('展示评论');
    let self = this;
    this.setData({
      showmore: true,
      shownum: self.data.shownum + 5,
    });
    if(self.data.shownum > self.data.evaluate.length){
      self.setData({
        havemore: false,
      })
    }
    for(let index in self.data.evaluate){
      if(index<self.data.shownum && index>self.data.shownum1){
       self.setData({
         evaluate1 : self.data.evaluate1.concat(self.data.evaluate[index]),
       })
      //  console.log('test');
      //  console.log(self.data.evaluate1);
      }
    }
    self.setData({
      shownum1: self.data.shownum1+5,
    });
    console.log(self.data.evaluate1);
  },


  onLoad: function (options) {
    console.log(options);
    var self = this;
    self.setData({
      userID: getApp().globalData.userID,
    })
    //猜你喜欢的商品
    wx.request({
      url: self.urlChange(this.data.toView, this.data.num),
      methods: 'GET',
      success: res=> {
        self.setData({
          detail: res.data.list,
        });
        self.incise();
      },
      error: res=>{
        console.log('请求失败！');
      },
    }),

    //请求评论信息
    wx.request({
      url: 'https://localhost:80/evaluate/queryByGId/'+options.goodsId,
      method:'GET',
      success: res=>{
        console.log(res);
        if(res.data.rows<1){
         console.log('没有更多');
         self.setData({
          havemore: false,
        })
        }else{
          self.setData({
            havemore: true,
            evaluate : res.data.rows,
            evanum: res.data.rows.length
          });
         for(let index in self.data.evaluate){
           if(index < self.data.shownum){
            self.setData({
              evaluate1: self.data.evaluate1.concat(self.data.evaluate[index]),
            })
            console.log('test');
            console.log(self.data.evaluate1);
           }

         }
          // console.log(self.data.evaluate);
        }
      
      },
      error: res=>{
        console.log('请求失败！');
      }
    }),


    // console.log(options.goodsId);
    //请求商品信息
    wx.request({
      url: 'https://localhost:80/goodsDetail/id_'+ options.goodsId +'/detail',
     
      method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      // header: {}, // 设置请求的 header
      success: res => {
        // success
        console.log('=================================================================');
        console.log(res.data);
        // console.log('请求的数据');
        console.log('=================================================================');
        let arr = [];
        let goodsImg = res.data.discountGoods.goods.goodsImg;
        arr = goodsImg.split(',');
        res.data.discountGoods.goods.goodsImg = arr;
        self.setData({
          assess: res.data.assess,
          goods: res.data.discountGoods.goods,  
          goodsDetail: res.data.goodsDetail,
          newPrice: res.data.discountGoods.newPrice,
          imgs: res.data.goodsDetail.goodsOtherImage,
        });
        self.incise3();
        if(self.data.imgs != null){
          self.setData({
            haveImgs : true,
          })
        }
        // console.log('======');
        // console.log(self.data.haveImgs);
        console.log('hahah');
        console.log(this.data.imgs);
      },
      fail: res=> {
        // fail
        console.log(res);
      },
      complete: function() {
        // complete
      }
    })
    
  },

  //下滑刷新函数
  loadMore() {
    let self = this;
    console.log('下滑刷新');
    if (self.data.ifnum) {
      if (self.data.toView != 'hot') {
        self.setData({
          num: self.data.num + 1
        })
        self.request();
      }
    }
  },

  //设置url函数
  urlChange(id, num) {
    return 'https://localhost:80/goods/' + id + '/' + num + '/goods';
  },

   //切割图片字符串函数
   incise(){
    let self = this;
    for(let index in self.data.detail){
      //整合了arr数组存放了正确的图片地址
      let str = self.data.detail[index].goods.goodsImg;
      let s = "detail["+index+"].goods.goodsImg";
      let arr = str.split(','); 
      // for(let i in arr){
      //   let item = arr[i];
      //   let answear =  'https://www.zhaoshenma.cn:80/images/' + item;
      //   arr[i] = answear;
      // }
 
      self.setData({
        [s]:arr,
      })
  
    }
  },

  //切割图片字符串函数
  incise2(){
    let self = this;
    let s = 'goods.goodsImg';
    let str = self.data.goods.goodsImg;
    let arr = str.split(',');
    // for(let index in arr){
    //   arr[index] = 'https://www.zhaoshenma.cn:80/images/' + arr[index];
    // }
    self.setData({
      [s]:arr
   })
  //  console.log(self.data.goods.goodsImg);
  },

  //切割图片字符串函数
  incise3(){
    let self = this;
    let s = 'imgs';
    let str = self.data.imgs;
    let arr = str.split(',');
    self.setData({
      [s]:arr
   })
  },
    //跳转函数
    jumpTo(e) {
      let self = this;
      console.log('准备跳转');
      console.log(e.currentTarget.dataset.index);
      let num = e.currentTarget.dataset.index;
      let id = self.data.detail[num].goods.goodsId;
      wx.navigateTo({
        url: '../../component/details/details?goodsId=' + id,
  
        success: function (res) {
          // success
          console.log('成功跳转');
        },
        fail: function () {
          // fail
          console.log('跳转失败');
        },
        complete: function () {
          // complete
          console.log('已请求');
        }
      })
    },

    //加购物车
    addshop(e) {
      let that = this;
      // console.log(e.currentTarget);
      console.log(e.target.dataset.index);
      let index = e.target.dataset.index;
  
      console.log(that.data.detail[index]);
      let item = that.data.detail[index];
      // console.log(item);
      // console.log(app.globalData.userID);
  
      let vip = getApp().globalData.vipState;
      let price = 0;
      if(vip == 1){
        price = item.goods.goodsPrice;
      }
      else{
        price = item.newPrice;
      }
      console.log(price);
      let userId = null;
      if (that.data.userID == null) {
        userId = wx.getStorageSync('userID');
      } else {
        userId = that.data.userID;
      }
      wx.request({
        url: 'https://localhost:80/cart/add',
        method: 'POST',
        data: {
          'cartGoods': {
            'goodsId': item.goods.goodsId,
            'goodsPrice': item.goods.goodsPrice
          },
          'cartNum': 1,
          'cartPrice': price,
          'cartUser': userId,
        },
        success: res => {
          console.log('成功');
          wx.showToast({
            title: '添加成功',
            icon: 'success',
            duration: 500
          })
        },
        error: res => {
          console.log('失败！');
          wx.showToast({
            title: '添加失败',
            icon: 'none',
            duration: 500
          })
        } 
      })
    },
    onShareAppMessage: function (ops) {

      let self = this;
      //转发事件来源。
      //button：页面内转发按钮；
      //menu：右上角转发菜单
  
      if (ops.from === 'button') {
        var title = ops.target.dataset.title;
      };
      console.log(self.data.goodsDetail);
      return {
        title: self.data.goods.goodsName, //转发的标题。当前小程序名称
      //   path: `pages/ordinaryDetails/ordinaryDetails?isShare=0`, //转发的路径
      //   imageUrl: '', //自定义图片路径 支持PNG及JPG。显示图片长宽比是 5:4。
      //   // success: function (res) {
      //   //     // 转发成功
      //   //     var shareTickets = res.shareTickets;
      //   //     api.showToast('转发成功');
      //   // },
      //   // fail: function (res) {
      //   //     // 转发失败
      //   //     api.showToast("转发失败:" + JSON.stringify(res));
      //   // }
  
      //   //由于版本更新，现在不能监听回调成功还是失败。
      //   //分享的内容是都会被成功发出
      //   //如果一定要回调的话可根据需求自定，目前小编还没有更好的办法。
      }
  
    },
})